﻿using System;
using System.Configuration;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using Channelvn.Cached.Common;
using System.Xml;
using System.Data;
using Channelvn.Cached;
using BAL;

namespace Rewrite.UrlRewrite
{
    public class RewriteModule : IHttpHandlerFactory, IRequiresSessionState
    {
        static string[] mobiles = new string[] {
                                                    "iphone","opera mini", "sony", "htc", "moto", "panasonic", "sharp", "philips", "samsung"
                                                    , "android", "nokia", "blackberry", "galaxy"
                                             };
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url1, string pathTranslated)
        {

            //Nếu user vào bằng ĐTDĐ thì đá sang trang m.dantri.com.vn
            if (IsMobileRedirect(context) || isMobileBrowser(context))
            {
                //if (!IsExistCookieNoRedirect())
                //    _301Redirection.RedirectToMobile("http://m.nld.com.vn" + context.Request.Url.AbsolutePath);
            }

         
            //if (HttpContext.Current.Request.Url.Query != String.Empty)
            //{
            //    if (context.Request.Url.Query.Length > 0)
            //    {
            //        context.Items["VirtualUrl"] = context.Request.Path + context.Request.Url.Query;
            //    }
            //}
            //if (context.Items["VirtualUrl"] == null)
            //{
            //    context.Items["VirtualUrl"] = context.Request.Path;
            //}
                        

            string url = context.Request.Url.AbsolutePath;
            string rewrite = "";

           
            RewriteRules rewriteRules = RewriteRules.GetCurrentRewriteRules();
            rewrite = rewriteRules.GetMatchingRewrite(url);

            if (!string.IsNullOrEmpty(rewrite))
            {
                context.RewritePath("~" + rewrite);
            }
            else
            {
                rewrite = context.Request.Path + context.Request.Url.Query;
            }

            string newFilePath = rewrite.IndexOf("?") > 0 ? rewrite.Substring(0, rewrite.IndexOf("?")) : rewrite;

            try
            {
                return PageParser.GetCompiledPageInstance(newFilePath, context.Server.MapPath(newFilePath), context);            
            }
            catch (Exception ex)
            {
                return PageParser.GetCompiledPageInstance("/404.aspx", context.Server.MapPath("/404.aspx"), context);
            }
            
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
        }
        private bool IsMobileRedirect(HttpContext context)
        {
            bool isReturn = false;
            if (context.Request.Browser["IsMobileDevice"] == "true")
            {
                isReturn = true;
            }
            return isReturn;
        }

        public bool isMobileBrowser(HttpContext context)
        {
            //GETS THE CURRENT USER CONTEXT
            // HttpContext context = HttpContext.Current;

            //FIRST TRY BUILT IN ASP.NT CHECK
            if (context.Request.Browser.IsMobileDevice)
            {
                return true;
            }
            //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
            if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
            {
                return true;
            }
            //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
            if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
                context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
            {
                return true;
            }
            //AND FINALLY CHECK THE HTTP_USER_AGENT 
            //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
            if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
            {



                //Loop through each item in the list created above 
                //and check if the header contains that text
                foreach (string s in mobiles)
                {
                    if (context.Request.ServerVariables["HTTP_USER_AGENT"].
                                                        ToLower().Contains(s.ToLower()))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        private bool IsExistCookieNoRedirect()
        {
            bool isReturn = false;
            string AbsolutePath = HttpContext.Current.Request.Url.Query;
            if (AbsolutePath.IndexOf("mobile=true") >= 0)
            {
                isReturn = true;
                HttpCookie cookie = new HttpCookie("browser", "web");
                try
                {
                    cookie.Expires = DateTime.Now.AddMinutes(30);
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
                catch (Exception ex)
                {
                }

            }
            else if (AbsolutePath.IndexOf("removecookie=true") >= 0)
            {
                isReturn = false;
                HttpCookie myCookie = HttpContext.Current.Request.Cookies.Get("browser");
                if (myCookie != null)
                    myCookie.Values.Clear();
            }
            else
            {

                HttpCookie myCookie = HttpContext.Current.Request.Cookies.Get("browser");
                if (myCookie != null && myCookie.Value.ToLower() == "web")
                {
                    isReturn = true;
                }


            }

            return isReturn;
        }
    }
}
